package org.mapdroid.utils;

import org.mapdroid.R;
import org.mapdroid.data.adt.MdService;
import org.mapdroid.maps.gmaps.MdMapActivity;
import org.mapdroid.maps.gmaps.overlay.MdMarkerItemizedOverlay;
import org.mapdroid.search.SearchAddressView;
import org.mapdroid.search.ServiceAddressView;
import org.mapdroid.search.ServiceCategoryView;
import org.mapdroid.search.ServiceNameView;

import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MdDirectionsActivity extends Activity implements OnClickListener, OnKeyListener{

	public static final String START_POINT 	= "START_POINT";
	public static final String START_TEXT	= "START_TEXT";
	public static final String END_POINT 	= "END_POINT";
	public static final String END_TEXT		= "END_TEXT";
	
	public static final String START_BUTTON = "START_BUTTON";
	public static final String END_BUTTON 	= "END_BUTTON";
	
	private TextView startPointTextView;
	private TextView endPointTextView;
	private ImageButton startPointButton;
	private ImageButton endPointButton;
	private Button okButton;
	private Button revertButton;
	
	private AlertDialog.Builder searchDialog;
	private AlertDialog.Builder searchServiceDialog;
	
	private Location startPoint;
	private Location endPoint;
	
	private int hasTapped;
	
	public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.directions_layout);
        
        startPointTextView = (TextView) findViewById(R.id.start_point_text_id);
        endPointTextView = (TextView) findViewById(R.id.end_point_text_id);
        startPointButton = (ImageButton) findViewById(R.id.start_point_button_id);
        endPointButton = (ImageButton) findViewById(R.id.end_point_button_id);
        okButton = (Button) findViewById(R.id.ok_directions_button);
        revertButton = (Button) findViewById(R.id.revert_directions_button);
        
        startPointTextView.setCursorVisible(false);
        startPointTextView.setInputType(InputType.TYPE_NULL);
        endPointTextView.setCursorVisible(false);
        endPointTextView.setInputType(InputType.TYPE_NULL);
        startPointTextView.setText(super.getIntent().getStringExtra(MdDirectionsActivity.START_TEXT));
        endPointTextView.setText(super.getIntent().getStringExtra(MdDirectionsActivity.END_TEXT));
        
        startPointTextView.setOnKeyListener(this);
        endPointTextView.setOnKeyListener(this);
        startPointButton.setOnClickListener(this);
        endPointButton.setOnClickListener(this);
        okButton.setOnClickListener(this);
        revertButton.setOnClickListener(this);
        
        startPoint 	= (Location) super.getIntent().getParcelableExtra(MdDirectionsActivity.START_POINT);
        if(startPoint == null)
        	startPoint = new Location(LocationManager.GPS_PROVIDER);

        endPoint 	= (Location) super.getIntent().getParcelableExtra(MdDirectionsActivity.END_POINT);
        if(endPoint == null)
        	endPoint = new Location(LocationManager.GPS_PROVIDER);
        
        hasTapped = -1;
        
        initDialog();
    }
    
	private void initDialog(){
		CharSequence[] searchVector = new CharSequence[2];
    	searchVector[MdMapActivity.SEARCH_ADDRESS_CONTEXT_CHOICE_ID] = getString(R.string.search_address_item);
    	searchVector[MdMapActivity.SEARCH_SERVICE_CONTEXT_CHOICE_ID] = getString(R.string.search_service_item);
    	
    	CharSequence[] searchVectorPosition = new CharSequence[3];
    	searchVectorPosition[0] = searchVector[0];
    	searchVectorPosition[1] = searchVector[1];
    	searchVectorPosition[2] = getString(R.string.my_position_text);

    	searchDialog = new AlertDialog.Builder(this);
    	searchDialog.setIcon(android.R.drawable.ic_input_get);
    	searchDialog.setTitle(R.string.show_indication_condensed_item);
		searchDialog.setSingleChoiceItems( (MdMapActivity.myPosition!=null) ? searchVectorPosition : searchVector, 
											-1, 
											new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch(which){
					case MdMapActivity.SEARCH_ADDRESS_CONTEXT_CHOICE_ID:
						Intent searchAddressIntent = new Intent(getBaseContext(), SearchAddressView.class);
		        		startActivityForResult(searchAddressIntent, MdMapActivity.SEARCH_ADDRESS_INTENT_ID);
		        		dialog.cancel();
		        		break;
					case MdMapActivity.SEARCH_SERVICE_CONTEXT_CHOICE_ID:
						dialog.cancel();
						searchServiceDialog.show();
						break;
					case 2:
						if(hasTapped==R.id.start_point_button_id){
							if(!pointsEquals(MdMapActivity.myPosition, endPoint)){
								startPointTextView.setText(R.string.my_position_text);
								startPoint = MdMapActivity.myPosition;
							}
							else{
								Toast.makeText(getBaseContext(), R.string.equals_points_error, Toast.LENGTH_SHORT).show();
							}
						}
						if(hasTapped == R.id.end_point_button_id){
							if(!pointsEquals(MdMapActivity.myPosition, startPoint)){
								endPointTextView.setText(R.string.my_position_text);
								endPoint = MdMapActivity.myPosition;
							}
							else{
								Toast.makeText(getBaseContext(), R.string.equals_points_error, Toast.LENGTH_SHORT).show();
							}
						}
						dialog.cancel();
						break;
				}
				return;
			}
		});
		
		CharSequence[] searchServiceVector = new CharSequence[3];
    	searchServiceVector[MdMapActivity.SEARCH_SERVICE_BY_NAME_CHOICE_ID] = getString(R.string.service_name_search);
    	searchServiceVector[MdMapActivity.SEARCH_SERVICE_BY_ADDRESS_CHOICE_ID] = getString(R.string.service_address_search);
    	searchServiceVector[MdMapActivity.SEARCH_SERVICE_BY_CATEGORY_CHOICE_ID] = getString(R.string.service_category_search);
		
		searchServiceDialog = new AlertDialog.Builder(this);
		searchServiceDialog.setIcon(android.R.drawable.ic_input_get);
		searchServiceDialog.setTitle(R.string.show_indication_condensed_item);
		searchServiceDialog.setSingleChoiceItems(searchServiceVector, -1, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Intent searchIntent = new Intent();
				searchIntent.putExtra(MdMarkerItemizedOverlay.LIST, MdMapActivity.serviceList);
				switch(which){
					case MdMapActivity.SEARCH_SERVICE_BY_NAME_CHOICE_ID:
						searchIntent.setClass(getBaseContext(), ServiceNameView.class);
						startActivityForResult(searchIntent, MdMapActivity.SEARCH_SERVICE_NAME_INTENT_ID);
						dialog.cancel();
		        		break;
					case MdMapActivity.SEARCH_SERVICE_BY_ADDRESS_CHOICE_ID:
						searchIntent.setClass(getBaseContext(), ServiceAddressView.class);
						startActivityForResult(searchIntent, MdMapActivity.SEARCH_SERVICE_ADDRESS_INTENT_ID);
						dialog.cancel();
						break;
					case MdMapActivity.SEARCH_SERVICE_BY_CATEGORY_CHOICE_ID:
						searchIntent.setClass(getBaseContext(), ServiceCategoryView.class);
						startActivityForResult(searchIntent, MdMapActivity.SEARCH_SERVICE_CATEGORY_INTENT_ID);
						dialog.cancel();
						break;
				}
				return;
			}
		});

	}
	
    @Override
    public void onDestroy() {
    	super.onDestroy();
    }
    
    @Override
    public void onPause(){
    	super.onPause();
    }

    @Override
    public void onResume(){
    	super.onResume();
    	okButton.setEnabled(startPointTextView.getText().length() > 0 && endPointTextView.getText().length() > 0);
    	if(pointsEquals(startPoint, endPoint)){
			endPointTextView.setText("");
		}
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int buttonId = v.getId();
		
		switch(buttonId){
			case R.id.start_point_button_id:
				hasTapped=R.id.start_point_button_id;
				searchDialog.show();
				break;
			
			case R.id.end_point_button_id:
				hasTapped=R.id.end_point_button_id;
				searchDialog.show();
				break;
				
			case R.id.ok_directions_button:
				Intent returnIntent = new Intent();
				returnIntent.putExtra(MdDirectionsActivity.START_POINT, startPoint);
				returnIntent.putExtra(MdDirectionsActivity.END_POINT, endPoint);
				setResult(Activity.RESULT_OK, returnIntent);
				finish();
				break;
				
			case R.id.revert_directions_button:
				CharSequence tmpString = startPointTextView.getText();
				startPointTextView.setText(endPointTextView.getText());
				endPointTextView.setText(tmpString);
				
				Location tmpLocation = startPoint;
				startPoint = endPoint;
				endPoint = tmpLocation;
				break;
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		super.onActivityResult(requestCode, resultCode, data);
		
		switch(requestCode){
			//Change the value of the activity menu after login
			case MdMapActivity.SEARCH_ADDRESS_INTENT_ID:
				if(resultCode == Activity.RESULT_OK){
					Address		address = data.getParcelableExtra(SearchAddressView.ADDRESS);
					String 		label	= data.getStringExtra(SearchAddressView.LABEL);
					GeoPoint 	pos		= new GeoPoint((int)(address.getLatitude()*1E6), (int)(address.getLongitude()*1E6));
					
					if(hasTapped == R.id.start_point_button_id){
						if(!pointsEquals(endPoint, pos)){
							startPointTextView.setText(label);
							startPoint.setLatitude(address.getLatitude());
							startPoint.setLongitude(address.getLongitude());
						}
						else{
							Toast.makeText(this, R.string.equals_points_error, Toast.LENGTH_SHORT).show();
						}
						
					}
					if(hasTapped == R.id.end_point_button_id){
						if(!pointsEquals(startPoint, pos)){
							endPointTextView.setText(label);
							endPoint.setLatitude(address.getLatitude());
							endPoint.setLongitude(address.getLongitude());
						}
						else{
							Toast.makeText(this, R.string.equals_points_error, Toast.LENGTH_SHORT).show();
						}
					}
					hasTapped = -1;
				}
			break;
			
			//View the results of a service search
			case MdMapActivity.SEARCH_SERVICE_ADDRESS_INTENT_ID:
			
			case MdMapActivity.SEARCH_SERVICE_NAME_INTENT_ID:
				
			case MdMapActivity.SEARCH_SERVICE_CATEGORY_INTENT_ID:
				if(resultCode == Activity.RESULT_OK){
					MdService service = data.getParcelableExtra(MdMarkerItemizedOverlay.OBJECT);
					GeoPoint pos = service.getPosition();
					String title = service.getName();
					
					if(pos==null || title==null)
						return;
					
					if(hasTapped == R.id.start_point_button_id){
						if(!pointsEquals(endPoint, pos)){
							startPointTextView.setText(title);
							startPoint.setLatitude(pos.getLatitudeE6()/1E6);
							startPoint.setLongitude(pos.getLongitudeE6()/1E6);
						}
						else{
							Toast.makeText(this, R.string.equals_points_error, Toast.LENGTH_SHORT).show();
						}
						
					}
					if(hasTapped == R.id.end_point_button_id){
						if(!pointsEquals(startPoint, pos)){
							endPointTextView.setText(title);
							endPoint.setLatitude(pos.getLatitudeE6()/1E6);
							endPoint.setLongitude(pos.getLongitudeE6()/1E6);
						}
						else{
							Toast.makeText(this, R.string.equals_points_error, Toast.LENGTH_SHORT).show();
						}
					}
					hasTapped = -1;
				}
			break;
		}
	}
	
	private boolean pointsEquals(Location start, Location end){
		if(start == null || end == null)
			return false;
		if(start.getLatitude() == end.getLatitude() && start.getLongitude() == end.getLongitude())
			return true;
		return false;
	}
	
	private boolean pointsEquals(Location start, GeoPoint end){
		if(start == null || end == null)
			return false;
		if(start.getLatitude() == end.getLatitudeE6()/1E6 && start.getLongitude() == end.getLongitudeE6()/1E6)
			return true;
		return false;
	}

	@Override
	public boolean onKey(View v, int arg1, KeyEvent arg2) {
		// TODO Auto-generated method stub
		switch (v.getId()){
			case R.id.start_point_text_id:
				if(pointsEquals(startPoint, endPoint)){
					endPointTextView.setText("");
				}
				break;
			case R.id.end_point_text_id:
				if(pointsEquals(startPoint, endPoint)){
					endPointTextView.setText("");
				}
				okButton.setEnabled(startPointTextView.getText().length() > 0 && endPointTextView.getText().length() > 0);
			break;
		}
		return false;
	}

}